﻿#region using
using System;
using System.Collections.Generic;
using AwesomeTanks.Sources.Media;
using AwesomeTanks.Sources.GameElements;
using AwesomeTanks.Sources.PlayerInputs;
#endregion

namespace AwesomeTanks.Sources.Screens
{
    /// <summary>
    /// Display the screen at the end of the game
    /// </summary>
    public class EndGameScreen : MenuScreen
    {
        #region Fields
        public const int END_Y_OFFSET = 300;
        public const int END_ENTRIES_MARGIN_Y = 30;

        /// <summary>
        /// The life bonus, ie the score granted at the end of the game in function of the remaining life of the players. 
        /// 1 life = +LIFE_BONUS pts.
        /// </summary>
        public const int LIFE_BONUS = 1000;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="EndGameScreen"/> class. 
        /// </summary>
        /// <param name="timeIsUp">True if the game is ended because the time is up. False otherwise.</param>
        public EndGameScreen(bool timeIsUp)
            : base("")
        {
            this.OffsetY = END_Y_OFFSET;
            this.MenuEntriesMarginY = END_ENTRIES_MARGIN_Y;

            // Stop all gamepads vibration and update the score
            List<Team> teams = GameplayScreen.listTeam;
            foreach (Team team in teams)
            {
                foreach (Player player in team.ListPlayers)
                {
                    if (player.Control is GamePadControlsState)
                    {
                        GamePadControlsState gamepad = (GamePadControlsState)player.Control;
                        gamepad.StopVibration();
                    }

                    player.Score += player.Life * LIFE_BONUS;
                }
            }

            if (timeIsUp)
            {
                this.MenuTitle = "                   Time's Up !";
            }
            else
            {
                String winner;
                if (OptionsMenuScreen.currentGameType == OptionsMenuScreen.GameType.TwoVsTwo)
                {
                    winner = getWinningTeam();
                }
                else
                {
                    winner = getWinningPlayer();
                }
                this.MenuTitle = String.Format("    {0} wins the fight !!", winner);
            }

            this.MenuTitle += String.Format("\n{0} is the MVP ! Congratz !", getMVP());

            // Create menu entries.
            MenuEntry replayMenuEntry = new MenuEntry("Replay !");
            MenuEntry returnToMainMenuMenuEntry = new MenuEntry("Return to main menu");

            // Hook up menu event handlers.
            replayMenuEntry.Selected += ReplayMenuEntrySelected;
            returnToMainMenuMenuEntry.Selected += ReturnToMainMenuMenuEntrySelected;

            // Add entries to the menu.
            MenuEntries.Add(replayMenuEntry);
            MenuEntries.Add(returnToMainMenuMenuEntry);

            // GameOver sound
            Sound.GameOver.Play();
        }
        #endregion

        #region Methods
        /// <summary>
        /// Handler when "Replays" entry is selected. Relaunch the game with the same options.
        /// </summary>
        /// <param name="sender">The sender of the event.</param>
        /// <param name="e">The <see cref="PlayerIndexEventArgs"/> instance containing the event data.</param>
        private void ReplayMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
                               new GameplayScreen());
        }

        /// <summary>
        /// Handler when "Return to main menu" entry is selected. Load the main menu.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReturnToMainMenuMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(Art.MENU_BACKGROUND_PATH),
                                                           new MainMenuScreen());
        }

        /// <summary>
        /// Gets the winning team of the game.
        /// </summary>
        /// <returns>The name of the winning team.</returns>
        private String getWinningTeam()
        {
            String winningTeam = "";
            List<Team> teams = GameplayScreen.listTeam;

            foreach (Team team in teams)
            {
                foreach (Player player in team.ListPlayers)
                {
                    if (player.Tank != null)
                    {
                        winningTeam = team.TeamColor.ToString();
                    }
                }
            }

            return String.Format("{0} Team", winningTeam); ;
        }

        /// <summary>
        /// Gets the winning player of the game.
        /// </summary>
        /// <returns>The name of the winning player.</returns>
        private String getWinningPlayer()
        {
            String winner = "";
            List<Team> teams = GameplayScreen.listTeam;

            foreach (Team team in teams)
            {
                foreach (Player player in team.ListPlayers)
                {
                    if (player.Tank != null)
                    {
                        winner = player.PlayerName;
                    }
                }
            }

            return winner;
        }

        /// <summary>
        /// Gets the Most Valuable Player of the game.
        /// </summary>
        /// <returns>The name of the MVP.</returns>
        public String getMVP()
        {
            List<Team> teams = GameplayScreen.listTeam;
            Player mvp = null;

            foreach (Team team in teams)
            {
                foreach (Player player in team.ListPlayers)
                {
                    if (mvp == null || mvp.Score < player.Score)
                    {
                        mvp = player;
                    }
                }
            }

            return mvp.PlayerName;
        }
        #endregion
    }
}
